using System;
using System.Data;
using System.Data.SqlClient;

namespace ObjectRelationalMapping.Helper
{
    internal class Sql
    {
        internal static SqlDataReader ExecuteReader (
            string commandText )
        {
            SqlCommand sqlCommand = new SqlCommand ();
            SqlConnection sqlConnection = 
                new SqlConnection ( 
                    Common.DatabaseConnectionString );
            SqlDataReader sqlDataReader = null;

            try
            {
                if ( sqlConnection.State != ConnectionState.Open )
                {
                    sqlConnection.Open ();
                }

                sqlCommand.Connection = sqlConnection;
                sqlCommand.CommandText = commandText;
                sqlCommand.CommandType = CommandType.Text;

                sqlDataReader =
                    sqlCommand.ExecuteReader ( 
                        CommandBehavior.CloseConnection );
            }
            catch
            {
                sqlConnection.Close ();
            }

            return sqlDataReader;
        }

        internal static void ExecuteNonQuery ( string commandText )
        {
            SqlCommand sqlCommand = new SqlCommand ();

            using ( SqlConnection sqlConnection =
                        new SqlConnection ( Common.DatabaseConnectionString ) )
            {
                if ( sqlConnection.State != ConnectionState.Open )
                {
                    sqlConnection.Open ();
                }
                sqlCommand.Connection = sqlConnection;
                sqlCommand.CommandText = commandText;
                sqlCommand.ExecuteNonQuery ();
            }
        }
    }
}